package com.jrx.anytxn.param.controller.system;

import com.google.common.collect.Maps;
import com.jrx.anytxn.i18n.annotation.IgnoreConvertField;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.param.dto.system.OrganizationTableReq;
import com.jrx.anytxn.param.dto.system.OrganizationTableRes;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;

/**
 * 机构表
 *
 * @author Yangxin
 * @date 2019/8/2
 */
@Api(tags = "机构参数API接口")
@RestController
@RequestMapping(value = "/param/organizations")
public class OrganizationTableController {
    private static final Logger logger= LoggerFactory.getLogger(OrganizationTableController.class);
    @Autowired
    IOrganizationTableService organizationTableService;
    @Autowired
    private InfoService infoService;

    @ApiOperation(value = "根据主键ID和租户ID查询机构表信息", notes = "通过id查询机构表信息")
    @GetMapping(value = "/{id}/{tenantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "主键",required = true),
            @ApiImplicitParam(name = "tenantId",value = "租户ID",required = true)
    })
    public TxnRespResult<OrganizationTableRes> getById(@NotNull @PathVariable Long id,@PathVariable("tenantId") String tenantId) {
        TxnRespResult<OrganizationTableRes> result = new TxnRespResult<>();
        OrganizationTableRes res;
        try {
            res = organizationTableService.findByIdAndTenId(id, String.valueOf(infoService.getUser().getProjectId()));
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "根据租户ID分页查询机构表信息",notes = "根据租户ID分页查询机构表信息")
    @GetMapping(value = "/pageNum/{pageNum}/pageSize/{pageSize}")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageNum",value="页码",required = true),
            @ApiImplicitParam(name="pageSize",value="页大小",required = true)})
    public TxnRespResult<TxnPage<OrganizationTableRes>> getAllPage(@PathVariable(value = "pageNum") Integer pageNum,@PathVariable(value = "pageSize") Integer pageSize) {

        TxnRespResult<TxnPage<OrganizationTableRes>> result = new TxnRespResult<>();
        TxnPage<OrganizationTableRes> response;
        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            response = organizationTableService.findAllPageByTenId(pageNum,pageSize,tenantId);
            result.getSuccess(response);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }

       return result;
    }

    @ApiOperation(value = "新增机构表信息",notes = "新增机构表信息")
    @PostMapping("/")
    public TxnRespResult<OrganizationTableRes> createOrganizationTable(@RequestBody OrganizationTableReq organizationTableReq) {
        OrganizationTableRes res;
        TxnRespResult<OrganizationTableRes> result = new TxnRespResult<>();
        try {
            organizationTableReq.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
            organizationTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = organizationTableService.addOrganizationTable(organizationTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "编辑机构表信息",notes = "编辑机构表信息")
    @PutMapping("/")
    public TxnRespResult<OrganizationTableRes> modifyOrganizationTable(@RequestBody OrganizationTableReq organizationTableReq) {
        TxnRespResult<OrganizationTableRes> result = new TxnRespResult<>();
        OrganizationTableRes res;
        try {
            organizationTableReq.setUpdateBy(infoService.getUser().getUserName());
            res = organizationTableService.modifyOrganizationTable(organizationTableReq);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }

        return result;
    }

    @ApiOperation(value = "根据ID和租户ID删除机构表信息",notes = "根据id和租户Id删除机构表信息")
    @DeleteMapping(value = "/{organizationId}/{tenantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "organizationId",value = "主键",required = true),
            @ApiImplicitParam(name = "tenantId",value = "租户ID",required = true)
    })
    public TxnRespResult<Boolean> removeById(@NotNull @PathVariable String organizationId,
                                             @PathVariable("tenantId") String tenantId) {
        TxnRespResult<Boolean> result = new TxnRespResult<>();
        Boolean flag;
        try {
            DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
            DeleteLogHelper.setDelleteHistory(deleteLog);

            flag = organizationTableService.removeByIdAndTenId(organizationId,String.valueOf(infoService.getUser().getProjectId()));
            result.getSuccess(flag);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        return result;
    }

    @ApiOperation(value = "获得机构表信息",notes = "获得机构表信息")
    @GetMapping(value = "/list")
    @IgnoreConvertField
    public TxnRespResult<HashMap<String, List<OrganizationTableRes>>> getAllOrg() {
        TxnRespResult<HashMap<String, List<OrganizationTableRes>>> result = new TxnRespResult<>();
        List<OrganizationTableRes> allOrg = organizationTableService.findAllOrgByTenId(String.valueOf(infoService.getUser().getProjectId()));

        HashMap<String, List<OrganizationTableRes>> sysCodeMap= Maps.newHashMap();
        sysCodeMap.put("listData",allOrg);
        return result.getSuccess(sysCodeMap);
    }

    @ApiOperation(value = "根据机构ID和租户ID查询机构表信息", notes = "通过id查询机构表信息")
    @PostMapping(value = "/get")
    public TxnRespResult<OrganizationTableRes> selectById(@RequestParam(value = "organizationId")String organizationId,
                                                          @RequestParam(value = "tenantId") String tenantId) {
        TxnRespResult<OrganizationTableRes> result = new TxnRespResult<>();
        OrganizationTableRes res = new OrganizationTableRes();
        try {
            PrOrganizationTable ress = organizationTableService.findByOrId(organizationId, tenantId);
            BeanUtils.copyProperties(ress,res);
            result.getSuccess(res);
        } catch (TxnException e) {
            logger.error(e.getMessage(),e);
            result.getFail(e.getErrCode(), e.getMessage());
        }
        return result;
    }

}
